package com.hmh.student.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmh.student.system.entity.SysRole;
import com.hmh.student.system.entity.SysUser;
import com.hmh.student.system.entity.SysUserRole;
import com.hmh.student.system.mapper.SysUserMapper;
import com.hmh.student.system.mapper.SysUserRoleMapper;
import com.hmh.student.system.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xyf
 * @since 2025-04-15
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
   @Autowired
  private SysUserRoleMapper sysUserRoleMapper;
    /**
     * 新增用户，并自动在用户角色表插入 userId（不分配角色）
     *
     * @return
     */
    @Transactional  // 保证事务
    public boolean addUser(SysUser sysUser) {
        // 1. 插入用户表（自动回填 userId）
        int userInsertCount = sysUserMapper.insert(sysUser);
        if (userInsertCount <= 0) {
            return false;
        }

        // 2. 插入用户角色表（仅设置 userId，roleId 为 null）
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(sysUser.getUserId()); // 使用自动生成的 userId
        int roleInsertCount = sysUserRoleMapper.insert(userRole);

        return roleInsertCount > 0;
    }





    //登录
    @Override
    public SysUser login(String userName,String password){
            return this.getOne(
                    new LambdaQueryWrapper<SysUser>()
                    .eq(SysUser::getUserName,userName)
                    .eq(SysUser::getPassword,password)
            );
    }


    //分页查询
    @Override
    public Page<SysUser> pageUser(String userName, Integer pageSize, Integer current) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        if (userName != null && !userName.isEmpty()) {
            wrapper.like("user_name", userName);
        }
        return this.page(new Page<>(current, pageSize), wrapper);
    }

    @Override
    public boolean existsById(Integer userId) {
        if (userId == null)  return false;
        return sysUserMapper.selectCount(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserId, userId)) > 0;
    }

}
